package com.example.todolist.view;

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.util.Log
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.example.todolist.R
import com.example.todolist.commen.TodoCategoryEnum
import com.example.todolist.commen.TodoImportance
import com.example.todolist.database.model.TodoEntity
import com.example.todolist.databinding.TodoListBinding
import com.example.todolist.entity.TodoCategory
import com.example.todolist.util.LoggerTag
import java.util.Collections

class TodoAdapter(
    private val toDetail: (Int) -> Unit,
    private val changeFinish: (Int, Boolean, Int) -> Unit,
    private val startDelMode: () -> Unit,
    val context: Context
) :
    ListAdapter<TodoCategory, TodoAdapter.TodoHolder>(TodoDiffCallback()), ItemTouchHelperAdapter {

    private val TV_PERSON = "负责人："
    private var isDelMode = false
    private var delSections = ArrayList<TodoEntity>()

    inner class TodoHolder(private val binding: TodoListBinding) :
        RecyclerView.ViewHolder(binding.root) {
        val container = binding.todoItemContainer
        private val tvCategory: TextView = binding.categoryText
        private val tvTitle: TextView = binding.todoTitle
        private val tvPerson: TextView = binding.todoPerson
        private val tvDdl: TextView = binding.todoDdl
        private val tvImportance: TextView = binding.importanceText
        private val tvExpired: TextView = binding.isExpired
        val checkFinish: CheckBox = binding.finishBox
        val delBox: CheckBox = binding.delBox

        fun bind(todo: TodoCategory) {

            // 正常信息处理
            tvTitle.text = todo.title
            tvDdl.text = todo.endTime
            tvPerson.text = "$TV_PERSON${todo.username}"
            tvCategory.text = todo.categoryName ?: TodoCategoryEnum.UNCATEGORY.content
            // 处理已过期待办的逻辑
            tvExpired.visibility = View.GONE
            if (todo.isExpired) {
                tvExpired.visibility = View.VISIBLE
            }
            checkFinish.visibility = View.GONE
            delBox.visibility = View.GONE
            // 处理删除模式
            if (isDelMode) {
                delBox.visibility = View.VISIBLE
                delBox.isChecked = todo.isSelected
            } else {
                checkFinish.visibility = View.VISIBLE
            }
            // 处理已完成待办的逻辑
            tvTitle.paintFlags = tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() // 先清除
            tvTitle.setTextColor(Color.GRAY)
            checkFinish.isChecked = false
            if (todo.isFinish) {
                tvTitle.paintFlags = tvTitle.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG // 再设置
                tvTitle.setTextColor(context.resources.getColor(R.color.progress_bg_purple))
                checkFinish.isChecked = true
            }
            // 优先级进行一下判断
            val todoImpo = TodoImportance.fromCode(todo.importance)
            tvImportance.text = todoImpo?.msg
            todoImpo?.let {
                val color = ContextCompat.getColor(context, it.colorId)
                val cardView =
                    itemView.findViewById<CardView>(R.id.cardview)
                cardView.setCardBackgroundColor(color)
            }
        }
    }

    // 创建viewHolder
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): TodoHolder {
        val viewHolder: TodoHolder
        //给holder绑定每一个item的view
//        val view = LayoutInflater.from(parent.context).inflate(R.layout.todo_list, parent, false)
        val binding = TodoListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        viewHolder = TodoHolder(binding)
        return viewHolder
    }

    // 绑定数据
    override fun onBindViewHolder(holder: TodoHolder, position: Int) {
        val todo = getItem(position) // ListAdapter 提供的方法
        holder.bind(todo)
        // 在这里写方法回调
        holder.container.setOnClickListener {
            if (isDelMode) {
                changeSections(todo, holder)
            } else {
                toDetail(todo.todoId)
            }
        }
        holder.container.setOnLongClickListener { v ->
            if (!isDelMode) {
                startAdapterDelMode()
            }
            true
        }
        holder.checkFinish.setOnClickListener {
            changeFinish(todo.todoId, !todo.isFinish, position)
//            notifyItemChanged(position)
        }
        holder.delBox.setOnClickListener {
            changeSections(todo, holder)
        }
    }

    override fun onItemMove(from: Int, to: Int) {
        val list = currentList.toMutableList()
        Collections.swap(list, from, to)
        submitList(list)
//        notifyItemMoved(from, to)
    }

    override fun getIsDelMode(): Boolean {
        return isDelMode
    }

    // 用于比较新旧数据的 DiffUtil 回调
    class TodoDiffCallback : DiffUtil.ItemCallback<TodoCategory>() {
        override fun areItemsTheSame(oldItem: TodoCategory, newItem: TodoCategory): Boolean {
            return oldItem.todoId == newItem.todoId // 比较唯一标识
        }

        @SuppressLint("DiffUtilEquals")
        override fun areContentsTheSame(oldItem: TodoCategory, newItem: TodoCategory): Boolean {
            return oldItem.equals(newItem) // 比较内容是否相同
        }
    }

    fun exitAdapterDelMode() {
        isDelMode = false
        initSelectedItems()
        notifyItemRangeChanged(0, itemCount) // 刷新所有项
    }

    private fun startAdapterDelMode() {
        Log.d(LoggerTag.MAIN_CATEGORY, "startAdapterDelMode: ${delSections}")
        isDelMode = true
        startDelMode()
        notifyItemRangeChanged(0, itemCount) // 刷新所有项
    }

    fun getSelectedItems() = delSections
    fun initSelectedItems() {
//        submitList(currentList)
        delSections.clear()
    }

    // 批量删除items的操作
    private fun changeSections(
        item: TodoCategory, holder: TodoHolder
    ) {
        if (isDelMode) {
            item.isSelected = !item.isSelected
            holder.delBox.isChecked = item.isSelected
            Log.d(LoggerTag.MAIN_TAG, "changeSections: ${item.todoId}")
            if (item.isSelected) {
                delSections.add(TodoEntity(id = item.todoId))
                Log.d(LoggerTag.MAIN_TAG, "changeSections: ${delSections}")
            } else {
                delSections.removeIf { it.id == item.todoId }
                Log.d(LoggerTag.MAIN_TAG, "changeSections: ${delSections}")
            }
        }
    }
}
